package com.steven.team.service

import com.alibaba.fastjson.JSONObject
import com.steven.team.config.SpringWebSocketHandler
import com.steven.team.dao.ChatDao
import com.steven.team.dao.FriendDao
import com.steven.team.pojo.ApplyFriend
import com.steven.team.utils.ResultUtils.DELETE_ERROR
import com.steven.team.utils.ResultUtils.INSERT_ERROR
import com.steven.team.utils.ResultUtils.SELECT_ERROR
import com.steven.team.utils.ResultUtils.SUCCESS_CODE
import com.steven.team.utils.ResultUtils.UPDATE_ERROR
import com.steven.team.utils.makeRes
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.socket.TextMessage

@Service
open class FriendServiceImp : FriendService {

    @Autowired
    val friendDao: FriendDao? = null

    @Autowired
    val webSocketHandler: SpringWebSocketHandler? = null

    override fun queryFriends(uid: Long): JSONObject {
        val jsonObject = JSONObject()
        return try {
            val friends = friendDao!!.queryFriends(uid)
            jsonObject["data"] = friends
            makeRes(SUCCESS_CODE, jsonObject)
        } catch (e: Exception) {
            jsonObject["msg"] = e.message
            e.printStackTrace()
            makeRes(SELECT_ERROR, jsonObject)
        }
    }

    override fun queryApplicationToSelf(uid: Long): JSONObject {
        val jsonObject = JSONObject()
        return try {
            jsonObject["data"] = friendDao!!.queryApplicationToSelf(uid)
            makeRes(SUCCESS_CODE, jsonObject)
        } catch (e: Exception) {
            jsonObject["msg"] = e.message
            e.printStackTrace()
            makeRes(SELECT_ERROR, jsonObject)
        }
    }

    override fun querySelfApplication(uid: Long): JSONObject {
        val jsonObject = JSONObject()
        return try {
            jsonObject["data"] = friendDao!!.querySelfApplication(uid)
            makeRes(SUCCESS_CODE, jsonObject)
        } catch (e: Exception) {
            jsonObject["msg"] = e.message
            e.printStackTrace()
            makeRes(SELECT_ERROR, jsonObject)
        }
    }

    override fun applyFriend(uid: Long, toUser: Long): JSONObject {
        val jsonObject = JSONObject()
        try {
            if (uid == toUser) {
                jsonObject["msg"] = "不能添加自己为好友！"
                makeRes(SUCCESS_CODE, jsonObject)
            }
            val bean = ApplyFriend()
            bean.applicantUser = uid
            bean.toUser = toUser
            bean.createTime = System.currentTimeMillis()
            friendDao!!.applyFriendRelationship(bean)
            println("id=${bean.id}")
            val jsonWs = JSONObject()
            jsonWs["type"] = "apply"
            jsonWs["data"] = friendDao.queryApplyFriendsById(bean.id)
            webSocketHandler!!.sendMessageToUser(toUser.toString(), TextMessage(jsonWs.toString()))
            return makeRes(SUCCESS_CODE, jsonObject)
        } catch (e: Exception) {
            jsonObject["msg"] = e.message
            e.printStackTrace()
            return makeRes(INSERT_ERROR, jsonObject)
        }
    }

    override fun agreeFriend(uid: Long, applicantUser: Long): JSONObject {
        val jsonObject = JSONObject()
        return try {
            val result = friendDao!!.updateFriendship(applicantUser, uid, true)
            if (result > 0) {
                friendDao.addFriendRelationship(applicantUser, uid)
                makeRes(SUCCESS_CODE, jsonObject)
            } else {
                throw Exception("更新失败！")
            }
        } catch (e: Exception) {
            jsonObject["msg"] = e.message
            e.printStackTrace()
            makeRes(UPDATE_ERROR, jsonObject)
        }
    }

    override fun refuseFriend(uid: Long, applicantUser: Long): JSONObject {
        val jsonObject = JSONObject()
        return try {
            val result = friendDao!!.updateFriendship(applicantUser, uid, false)
            if (result > 0) {
                makeRes(SUCCESS_CODE, jsonObject)
            } else {
                throw Exception("更新失败！")
            }
            makeRes(SUCCESS_CODE, jsonObject)
        } catch (e: Exception) {
            jsonObject["msg"] = e.message
            e.printStackTrace()
            makeRes(UPDATE_ERROR, jsonObject)
        }
    }

    override fun updateToUserApplicantReadStatus(toUser: Long): JSONObject {
        val jsonObject = JSONObject()
        return try {
            val result = friendDao!!.updateToUserApplicantReadStatus(toUser)
            if (result > 0) {
                makeRes(SUCCESS_CODE, jsonObject)
            } else {
                throw Exception("更新失败！")
            }
        } catch (e: Exception) {
            jsonObject["msg"] = e.message
            e.printStackTrace()
            makeRes(UPDATE_ERROR, jsonObject)
        }
    }

    @Transactional
    override fun deleteFriend(uid: Long, friendId: Long): JSONObject {
        val jsonObject = JSONObject()
        return try {
            friendDao!!.deleteFriend(uid, friendId)
            friendDao.deleteFriend(friendId, uid)
            makeRes(SUCCESS_CODE, jsonObject)
        } catch (e: Exception) {
            jsonObject["msg"] = e.message
            e.printStackTrace()
            makeRes(DELETE_ERROR, jsonObject)
        }
    }

    override fun queryUserDetail(friendId: Long, selfId: Long): JSONObject {
        val jsonObject = JSONObject()
        try {
            if (friendId == selfId) {
                jsonObject["msg"] = "不能添加自己为好友！"
                return makeRes(SUCCESS_CODE, jsonObject)
            }
            val res = friendDao!!.queryUserDetail(friendId)
            return if (res.isNotEmpty()) {
                jsonObject["data"] = res[0]
                jsonObject["isFriend"] = friendDao.query2UserIsFriends(selfId, friendId).size >= 2
                makeRes(SUCCESS_CODE, jsonObject)
            } else {
                jsonObject["msg"] = "没有此人"
                makeRes(SUCCESS_CODE, jsonObject)
            }
        } catch (e: Exception) {
            jsonObject["msg"] = e.message
            e.printStackTrace()
            return makeRes(SELECT_ERROR, jsonObject)
        }
    }

    override fun queryChatFriends(uid: Long): JSONObject {
        val jsonObject = JSONObject()
        return try {
            jsonObject["data"] = friendDao?.queryChatFriends(uid)
            makeRes(SUCCESS_CODE, jsonObject)
        } catch (e: Exception) {
            jsonObject["msg"] = e.message
            e.printStackTrace()
            makeRes(SELECT_ERROR, jsonObject)
        }
    }
}